package com.fly.jwt;

import java.util.Base64;
import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;

/**
 * jwt加密和解密的工具类
 * 
 * @author 00fly
 * @version [版本号, 2021年12月21日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
public class JwtUtils
{
    /**
     * 签发JWT
     * 
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String createJwt(String id, String subject, long ttlMillis)
    {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
            .setId(id)
            .setSubject(subject) // 主题
            .setIssuer("00fly") // 签发者
            .setIssuedAt(now) // 签发时间
            .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis >= 0)
        {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }
    
    /**
     * 验证JWT
     * 
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJwt(String jwtStr)
    {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try
        {
            claims = parseJwt(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        }
        catch (ExpiredJwtException e)
        {
            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE);
            checkResult.setSuccess(false);
        }
        catch (SignatureException e)
        {
            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        }
        catch (Exception e)
        {
            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        }
        return checkResult;
    }
    
    private static SecretKey generalKey()
    {
        byte[] encodedKey = Base64.getDecoder().decode(SystemConstant.JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    
    /**
     * 
     * 解析JWT字符串
     * 
     * @param jwt
     * @return
     * @throws Exception
     */
    private static Claims parseJwt(String jwt)
    {
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }
    
    public static void main(String[] args)
    {
        String sc = createJwt("1", "小明", 3000);
        log.info("jwt: {}", sc);
        CheckResult result = validateJwt(sc);
        log.info("checkresult: {}", ToStringBuilder.reflectionToString(result, ToStringStyle.JSON_STYLE));
    }
}
